import { Component, ViewChild } from '@angular/core';
import { DataTableComponent, DialogService, DrawerService, TableWidthConfig, IDrawerOpenResult } from '@devui';
import { LogComponent } from 'src/app/@shared/components/log/log.component';
import { environment } from 'src/environments/environment';
import { InventoryRkComponent } from '../product-inventory-rk/inventory-rk/inventory-rk.component';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { Router } from '@angular/router';
import { StorehouseService } from 'src/app/@core/services/storehouse/storehouse.service';
import { JobOrderService } from 'src/app/@core/services/jobOrder/job-order.service';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';

@Component({
  selector: 'app-inventory-warning',
  templateUrl: './inventory-warning.component.html',
  styleUrls: ['./inventory-warning.component.scss']
})
export class InventoryWarningComponent {
  value1 = [];
  tableData: any[] = []
  productionWarehousingNum: string = ''
  DateTime: any = null
  startTime: any = null
  endTime: any = null
  allCheckedStatus = false;
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20
  };
  checkedIds = [];
  pageSizeOptions = [10, 20, 30, 50, 100];
  msgs: { severity: any; summary: any; content: any; }[];
  config = {
    id: 'Add-role',
    maxHeight: '400px',
    width: '400px',
    backdropCloseable: true,
  }//弹窗配置
  filterValue: string = '';
  TreeData: any = [];
  employCode: any;
  @ViewChild(DataTableComponent, { static: true }) datatable: DataTableComponent;
  state: any;
  constructor(private dialogService: DialogService, private SharedMethodService: SharedMethodService, private Router: Router, private StorehouseService: StorehouseService, private JobOrderService: JobOrderService, private drawerService: DrawerService, private EncodeRulesService: EncodeRulesService) {
    this.employCode = JSON.parse(localStorage.getItem('userinfo')).employeeCode;
  }
  ngOnInit(): void {
    this.JobOrderService.GetProductionWarehousingPaged(this.productionWarehousingNum, this.startTime, this.endTime, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.tableData = (data.items || []).map((x: any) => ({
        ...x,
        inboundTime: this.getInboundTime(x),
        inboundDurationDays: this.calcHalfDayDurationSince(this.getInboundTime(x))
      }))
      this.pager.total = data.totalCount
    })
  }
  dataTableOptions = {
    columns: [
      {
        field: '生产入库单号',
        header: '生产入库单号',
        fieldType: 'text',
      },
      {
        field: '单据类型',
        header: '单据类型',
        fieldType: 'text',
      },
      {
        field: '工单号',
        header: '工单号',
        fieldType: 'text',
      },
      {
        field: '销售单号',
        header: '销售单号',
        fieldType: 'text'
      },
      {
        field: '客户简称',
        header: '客户简称',
        fieldType: 'text'
      },
      {
        field: '客户名称',
        header: '客户名称',
        fieldType: 'text'
      },
      {
        field: '客户联系人',
        header: '客户联系人',
        fieldType: 'text'
      },
      {
        field: '产品编码',
        header: '产品编码',
        fieldType: 'text'
      },
      {
        field: '产品名称',
        header: '产品名称',
        fieldType: 'text'
      },
      {
        field: '是否检验',
        header: '是否检验',
        fieldType: 'text'
      },
      {
        field: '规格',
        header: '规格',
        fieldType: 'text'
      },
      {
        field: '生产数量',
        header: '生产数量',
        fieldType: 'text'
      },
      {
        field: '已入库数量',
        header: '已入库数量',
        fieldType: 'text'
      },
      {
        field: '单位',
        header: '单位',
        fieldType: 'text'
      },
      {
        field: '入库时间',
        header: '入库时间',
        fieldType: 'text'
      },
      {
        field: '入库时长(天/半天)',
        header: '入库时长(天/半天)',
        fieldType: 'text'
      },

      {
        field: '二维码',
        header: '二维码',
        fieldType: 'text'
      },
      {
        field: '报工人',
        header: '报工人',
        fieldType: 'text'
      },
      {
        field: '报工时间',
        header: '制单时间',
        fieldType: 'text'
      },
      {
        field: '状态',
        header: '状态',
        fieldType: 'text'
      },
      {
        field: '是否核准',
        header: '是否核准',
        fieldType: 'text'
      },
      {
        field: '备注',
        header: '备注',
        fieldType: 'text'
      },
      {
        field: '日志',
        header: '日志',
        fieldType: 'text'
      },
    ]
  }//表格数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: '生产入库单号',
      width: '160px'
    },
    {
      field: '单据类型',
      width: '160px'
    },
    {
      field: '工单号',
      width: '150px'
    },
    {
      field: '客户简称',
      width: '150px'
    },
    {
      field: '客户名称',
      width: '180px'
    },
    {
      field: '客户联系人',
      width: '150px'
    },

    {
      field: '产品编码',
      width: '150px'
    },
    {
      field: '产品名称',
      width: '150px'
    },
    {
      field: '是否检验',
      width: '150px'
    },
    {
      field: '规格',
      width: '100px'
    },
    {
      field: '入库数量',
      width: '100px'
    },
    {
      field: '入库数量',
      width: '100px'
    },
    {
      field: '单位',
      width: '100px'
    },
    {
      field: '入库时间',
      width: '170px'
    },
    {
      field: '入库时长(天/半天)',
      width: '150px'
    },
    {
      field: '报工人',
      width: '100px'
    },
    {
      field: '报工时间',
      width: '150px'
    },
    {
      field: '状态',
      width: '100px'
    },
    {
      field: '是否核准',
      width: '100px'
    },
    {
      field: '备注',
      width: '100px'
    },
    {
      field: '日志',
      width: '100px'
    },
  ]//表格宽度配置
  pageIndexChange($event: any) {
    this.pager.pageIndex = $event;
    this.JobOrderService.GetProductionWarehousingPaged(this.productionWarehousingNum, this.startTime, this.endTime, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.tableData = (data.items || []).map((x: any) => ({
        ...x,
        inboundTime: this.getInboundTime(x),
        inboundDurationDays: this.calcHalfDayDurationSince(this.getInboundTime(x))
      }))
      this.pager.total = data.totalCount
    })
  }//切换页码
  pageSizeChange($event: any) {
    this.JobOrderService.GetProductionWarehousingPaged(this.productionWarehousingNum, this.startTime, this.endTime, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.tableData = (data.items || []).map((x: any) => ({
        ...x,
        inboundTime: this.getInboundTime(x),
        inboundDurationDays: this.calcHalfDayDurationSince(this.getInboundTime(x))
      }))
      this.pager.total = data.totalCount
    })
  }//改变每页显示数量
  DeleteRole(rowitem: any, dialogtype?: string) {
    const results = this.dialogService.open({
      ...this.config,
      title: '删除单据',
      content: '确认删除该入库单据吗？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.StorehouseService.DeleteOtherWarehousingModel(rowitem.otherWarehousingModelId).subscribe((data: any) => {
              this.StorehouseService.getWarehouseById(rowitem.warehouseId).subscribe((data: any) => {
                rowitem.warehouseName = data.warehouseName
              })
              this.showToast('success', '成功', '删除成功')

            }, (error) => {
              if (error.status == 404) {
                this.showToast('error', '失败', '服务器连接失败');
              } else {
                this.showToast('error', '失败', error.error);
              }
              results.modalInstance.hide();
            })
            results.modalInstance.hide();
            this.JobOrderService.GetProductionWarehousingPaged(this.productionWarehousingNum, this.startTime, this.endTime, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
              this.tableData = data.items
              this.pager.total = data.totalCount
            })
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//删除
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  add() {
    this.Router.navigate(['/pages/inventory/initial-inventory/add'])
  }//新增
  edit(id: any) {
    this.Router.navigate(['/pages/inventory/initial-inventory/edit', id]);
  }
  filter() {
    this.JobOrderService.GetProductionWarehousingPaged(this.productionWarehousingNum, this.startTime, this.endTime, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.tableData = (data.items || []).map((x: any) => ({
        ...x,
        inboundTime: this.getInboundTime(x),
        inboundDurationDays: this.calcHalfDayDurationSince(this.getInboundTime(x))
      }))
      this.pager.total = data.totalCount
    })
  }//搜索
  filter2() {
    this.pager.pageIndex = 1
    this.JobOrderService.GetProductionWarehousingPaged(this.productionWarehousingNum, this.startTime, this.endTime, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.tableData = (data.items || []).map((x: any) => ({
        ...x,
        inboundTime: this.getInboundTime(x),
        inboundDurationDays: this.calcHalfDayDurationSince(this.getInboundTime(x))
      }))
      this.pager.total = data.totalCount
    })
  }//搜索
  reset() {
    this.productionWarehousingNum = ''
    this.DateTime = null
    this.startTime = null
    this.endTime = null
    this.value1 = []
    this.JobOrderService.GetProductionWarehousingPaged(this.productionWarehousingNum, this.startTime, this.endTime, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.tableData = (data.items || []).map((x: any) => ({
        ...x,
        inboundTime: this.getInboundTime(x),
        inboundDurationDays: this.calcHalfDayDurationSince(this.getInboundTime(x))
      }))
      this.pager.total = data.totalCount
    })
  }//重置
  onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; }) {
    this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem, this.datatable)
  }
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(this.datatable, 'workshopId').subscribe((data: any) => {
      this.checkedIds = data;
    })
  }//获取选中行
  cleared() {
    this.SharedMethodService.cleared(this.checkedIds, this.tableData, this.datatable).subscribe((data: any) => {
      this.checkedIds = data;
    })
  }//清空选中行
  start$end() {
    this.startTime = this.value1[0].toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '/');
    this.endTime = this.value1[1].toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '/');
  }
  detailed(id: any) {
    this.Router.navigate(['/pages/inventory/initial-inventory/details', id]);
  }
  // 计算最近入库时间：优先使用明细的时间字段，其次 fallback 到单据日期
  private getInboundTime(row: any): string | null {
    try {
      const details = row?.productionWarehousingDetails || row?.productionWarehousingEntryDetailsDtos || [];
      const times: number[] = (details || [])
        .map((d: any) => d?.warehousingTime || d?.entryTime || d?.createTime)
        .filter((t: any) => !!t)
        .map((t: any) => new Date(t).getTime())
        .filter((n: number) => !isNaN(n));
      if (times.length > 0) {
        const latest = Math.max(...times);
        return new Date(latest).toISOString();
      }
      if (row?.dateTime) {
        const dt = new Date(row.dateTime).getTime();
        return isNaN(dt) ? null : new Date(dt).toISOString();
      }
      return null;
    } catch {
      return null;
    }
  }
  // 基于 12 小时为半天，计算距今入库时长（天/半天，向上取）
  private calcHalfDayDurationSince(when?: string | null): number | null {
    if (!when) return null;
    const t = new Date(when).getTime();
    if (isNaN(t)) return null;
    const hours = (Date.now() - t) / (1000 * 60 * 60);
    if (hours <= 0) return 0;
    return Math.ceil(hours / 12) / 2;
  }
  ruku(rowitem: any, dialogtype?: string) {
    const results = this.dialogService.open({
      ...this.config,
      title: '生产入库',
      width: '900px',
      data: rowitem,
      content: InventoryRkComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            let inspectionOrderNum = ""
            if (rowitem.orderType == '委外入库') {
              this.EncodeRulesService.GenerateWarehouseCodeRule('委外质检单', '委外质检单').subscribe((data: any) => {
                inspectionOrderNum = data
                this.ProductionWarehousing(rowitem, results, inspectionOrderNum)
              })
            } else {
              this.ProductionWarehousing(rowitem, results)
            }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  ProductionWarehousing(rowitem: any, results: any, inspectionOrderNum?: string) {
    this.JobOrderService.ProductionWarehousing({
      employeeCode: this.employCode,
      productionWarehousingId: rowitem.id,
      productionWarehousingEntryDetailsDtos: results.modalContentInstance.tableData.map((item: any) => ({
        warehouseId: item.warehouseId,
        positionId: item.positionId,
        quantity: item.quantity,
  warningDate: item.warningDate || null,
        inspectionOrderNum: inspectionOrderNum || '',
      }))
    }).subscribe((data: any) => {
      this.showToast('success', '成功', '入库成功')
      this.JobOrderService.GetProductionWarehousingPaged(this.productionWarehousingNum, this.startTime, this.endTime, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
        this.tableData = data.items
        this.pager.total = data.totalCount
      })
      results.modalInstance.hide();
    }, (error: any) => {
      this.showToast('danger', '错误', error.error)
    }
    )
  }
  isAudit(rowitem: any) {
    this.JobOrderService.AuditProductionWarehousing(rowitem.id).subscribe((data: any) => {
      this.showToast('success', '成功', '审核成功')
      this.JobOrderService.GetProductionWarehousingPaged(this.productionWarehousingNum, this.startTime, this.endTime, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
        this.tableData = data.items
        this.pager.total = data.totalCount
      })
    }, (error: any) => {
      this.showToast('danger', '错误', error.error || '服务器连接失败')
    }
    )
  }
  results: IDrawerOpenResult;
  GetLogs() {
    this.StorehouseService.GetAllProductionWarehousingLogs(1, 9999).subscribe((data: any) => {
      const logData = data.items
      const columns = [
        {
          field: '生产入库单号',
          header: '生产入库单号',
          fieldType: 'text'
        },
        {
          field: 'content',
          header: '日志内容',
          fieldType: 'text'
        },
        {
          field: '执行人',
          header: '执行人',
          fieldType: 'text'
        },
        {
          field: '执行时间',
          header: '执行时间',
          fieldType: 'text'
        }
      ]

      this.results = this.drawerService.open({
        drawerContentComponent: LogComponent,
        width: '40%',
        data: { data: logData, columns: columns },
        zIndex: 1000,
        isCover: false,
        fullScreen: true,
        backdropCloseable: true,
        escKeyCloseable: true,
        position: 'right',
        resizable: true,
        onClose: () => {

        },
      });
    })
  }
  GetLogById(rowItem: any) {
    this.StorehouseService.GetLogsByProductionWarehousingId(rowItem.id, 1, 9999).subscribe((data: any) => {
      const logData = data.items
      const columns = [
        {
          field: '生产入库单号',
          header: '生产入库单号',
          fieldType: 'text'
        },
        {
          field: 'content',
          header: '日志内容',
          fieldType: 'text'
        },
        {
          field: '执行人',
          header: '执行人',
          fieldType: 'text'
        },
        {
          field: '执行时间',
          header: '执行时间',
          fieldType: 'text'
        }
      ]

      this.results = this.drawerService.open({
        drawerContentComponent: LogComponent,
        width: '40%',
        data: { data: logData, columns: columns },
        zIndex: 1000,
        isCover: false,
        fullScreen: true,
        backdropCloseable: true,
        escKeyCloseable: true,
        position: 'right',
        resizable: true,
        onClose: () => {

        },
      });
    })
  }
  calculateEntryQuantitySum(data: any): any {
    return data.productionWarehousingDetails.reduce((sum: number, detail: any) => {
      return sum + detail.entryQuantity;
    }, 0);
  }
  UnAuditProductionWarehousing(rowitem: any) {
    this.StorehouseService.UnAuditProductionWarehousing(rowitem.id, this.employCode).subscribe((data: any) => {
      this.showToast('success', '成功', '反审核成功')
      this.JobOrderService.GetProductionWarehousingPaged(this.productionWarehousingNum, this.startTime, this.endTime, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
        this.tableData = data.items
        this.pager.total = data.totalCount
      })
    },
      (error: any) => {
        this.showToast('danger', '错误', error.error || '服务器连接失败')
      }
    )
  }
  getImagesArray2(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map(url => environment.modifiedApiUrl + '/' + url);
    return urls;
  }
}
